import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { getTopPlaylistAPI, getTopPlaylistHighqualityAPI } from "../api";
import { getToplistAPI, getrcmdSongMenuAPI } from "@/views/home/api";
import { RootState } from "@/store";

interface IState {
  topPlatList: any[],
  results: any[],
  highqualist: any[],
  lasttime: number,
  rankings: any[]
}

const initialState: IState = {
  topPlatList: [],
  results: [],
  lasttime: 0,
  highqualist: [],
  rankings: []
}

interface IPlayListArg {
  limit?: number,
  offset?: number,
  cat: string
}

// 获取 all一般的歌单列表
export const feachTopplayListAction = createAsyncThunk<void, IPlayListArg, { state: RootState }>("topplaylist", async (arg, { dispatch, getState }) => {
  const { limit = 50, cat, offset = 0 } = arg
  const { playlists } = await getTopPlaylistAPI(cat, offset, limit)
  const state = getState()
  const newToplist = state.discoverPage.topPlatList

  let newPlaylists: any[] = []
  if (offset === 0) {
    newPlaylists = playlists
    dispatch(replaceTopPlayListAction(newPlaylists))
  } else {
    newToplist.forEach(pl => {
      const finalIndex = playlists.findIndex((item: any) => item !== pl)
      if (finalIndex === -1) {
        newPlaylists.push(pl)
      }
    })
    dispatch(changeTopPlayListAction(newPlaylists))
  }

})

// 获取推荐歌单
export const feachrcmdSongMenuAction = createAsyncThunk("rcmdsongmenu", async (arg, { dispatch }) => {
  const { result } = await getrcmdSongMenuAPI(100)
  dispatch(changeResultsAction(result))
})

interface IRankingArg {
  limit?: number,
  before?: number
}

// 获取精品歌单
export const feachHighqualityAction = createAsyncThunk<void, IRankingArg>("highquality", async (arg, { dispatch }) => {
  const { limit = 50, before = 0 } = arg
  const { lasttime, playlists } = await getTopPlaylistHighqualityAPI(limit, before)
  dispatch(changeHighqualityAction({ lasttime, playlists }))
})

// 获取排行榜
export const feachRankingAction = createAsyncThunk("ranking", async (arg, { dispatch }) => {
  const { list } = await getToplistAPI()
  dispatch(changeRankingAction(list))
})

const discoverPageSlice = createSlice({
  name: "discoverPage",
  initialState,
  reducers: {
    changeTopPlayListAction(state, { payload }) {
      state.topPlatList = [...state.topPlatList, ...payload]
    },
    replaceTopPlayListAction(state, { payload }) {
      state.topPlatList = payload
    },
    changeResultsAction(state, { payload }) {
      state.results = payload
    },
    changeHighqualityAction(state, { payload }) {
      const { lasttime, playlists } = payload
      state.lasttime = lasttime
      state.highqualist = [...state.highqualist, ...playlists]
    },
    changeRankingAction(state, { payload }) {
      state.rankings = payload
    }
  }
})

export const { changeTopPlayListAction, replaceTopPlayListAction, changeResultsAction, changeHighqualityAction, changeRankingAction } = discoverPageSlice.actions
export default discoverPageSlice.reducer